package io.BIO;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;

public class ServerBIO {
    public static List<Socket> socketList = new ArrayList<>();

    public static void main(String[] args) throws IOException {
        //开启一个 TCP 服务端,占用一个本地端口
        ServerSocket serverSocket = new ServerSocket(12138);
        //服务端循环不断地接受客户端的连接
        System.out.println("server start...");
        while (true) {
            Socket socket;
            try {
                socket = serverSocket.accept();
                socketList.add(socket);
                System.out.println("客户端" + socket.getRemoteSocketAddress() + "上线了");
                //为每一个客户端分配一个线程
                Thread workThread = new Thread(new ServerHandler(socket));
                workThread.start();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}

class ServerHandler implements Runnable {
    private Socket socket;
    private BufferedReader socketBufferedReader;

    public ServerHandler(Socket socket) throws IOException {
        this.socket = socket;
        this.socketBufferedReader = new BufferedReader(new InputStreamReader(socket.getInputStream()));
    }

    @Override
    public void run() {
        try {
            //从 Socket 中获得输入输出流,接收和发送数据
            String msg;
            while ((msg = readMsgFromClient()) != null) {
                System.out.println("收到来自客户端" + socket.getRemoteSocketAddress() + "的消息：" + msg);
                String massMsg = "客户端【" + socket.getRemoteSocketAddress() + "】说：" + msg;
                for (Socket socket : ServerBIO.socketList) {
                    PrintWriter socketPrintWriter = new PrintWriter(socket.getOutputStream(), true);
                    socketPrintWriter.println(massMsg);
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //当与一个客户端通信结束后，需要关闭对应的 socket
            if (socket != null) {
                try {
                    socket.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private String readMsgFromClient() {
        try {
            return socketBufferedReader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            //如果捕获到异常，则将该客户端对应的 socket 删除
            ServerBIO.socketList.remove(socket);
        }
        return null;
    }
}